import 'dart:convert';
import 'dart:io';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/fwebView_scaffold.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:gzmall_app/model/user.dart';
import 'home/home_widget.dart';
import 'category/category_widget.dart';
import 'shoppping_cart/shopping_cart_widget.dart';
import 'mine/mine_widget.dart';
import 'common/color_common.dart';
import 'package:amap_location/amap_location.dart';
import 'home/scan_widget.dart';

class HomePage extends StatefulWidget {
  int currentIndex = 0;
  int categoryRootId = 0;

  HomePage({this.currentIndex = 0, this.categoryRootId = 0});

  @override
  _HomePageState createState() => _HomePageState(
      currentIndex: this.currentIndex, categoryRootId: this.categoryRootId);
}

class _HomePageState extends State<HomePage> {
  int currentIndex = 0;
  int categoryRootId = 0;
  List<Widget> _children = [];

  var _titles;
  var _tabImages;

  _HomePageState({this.currentIndex = 0, this.categoryRootId = 0});

  @override
  void initState() {
    super.initState();

    LaunchUtil.initCanLaunch();
    Future.delayed(Duration.zero, () {
      SettingUtil.init(context);
    });

    _children.add(HomeWidget(onSelectTab: _onSelectTab));
    _children
        .add(CategoriesPage(rootId: categoryRootId, onSelectTab: _onSelectTab));
    _children.add(ScanWidget());
    _children.add(ShoppingCartWidget(onSelectTab: _onSelectTab));
    _children.add(MineWidget(onSelectTab: _onSelectTab));

    _initLocation();
  }

  _initLocation() async {
    await AMapLocationClient.startup(AMapLocationOption(
        desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyHundredMeters));

    Future.delayed(const Duration(milliseconds: 3000), () {
      if (Platform.isAndroid) {
        User.getIsShowPrivacy().then((v) {
          if (!v || v == null) {
            _showPrivacyDialog();
          }
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    initData();
    return WillPopScope(
        onWillPop: _requestPop,
        child: Scaffold(
          body: IndexedStack(
            index: currentIndex,
            children: _children,
          ),
          bottomNavigationBar: BottomNavigationBar(
            onTap: onTabTapped,
            currentIndex: 0,
            iconSize: 20.0,
            type: BottomNavigationBarType.fixed,
            items: [
              BottomNavigationBarItem(
                icon: getTabIcon(0),
                title: getTabTitle(0),
              ),
              BottomNavigationBarItem(
                icon: getTabIcon(1),
                title: getTabTitle(1),
              ),
              BottomNavigationBarItem(
                icon: getTabIcon(2),
                title: getTabTitle(2),
              ),
              BottomNavigationBarItem(
                icon: getTabIcon(3),
                title: getTabTitle(3),
              ),
              BottomNavigationBarItem(
                icon: getTabIcon(4),
                title: getTabTitle(4),
              ),
            ],
          ),
        ));
  }

  void onTabTapped(int index) {
    if (index == 2) {
      _scan();
      return;
    }
    if (!mounted) return;
    setState(() {
      currentIndex = index;
      if (index == 3) {
        (_children[index] as ShoppingCartWidget)?.initData();
      }
    });
  }

  Image getTabIcon(int curIndex) {
    if (curIndex == currentIndex) {
      return _tabImages[curIndex][1];
    }
    return _tabImages[curIndex][0];
  }

  Widget getTabTitle(int curIndex) {
    if (curIndex == currentIndex) {
      return Padding(
          padding: const EdgeInsets.only(top: 4.0),
          child: Text(
            _titles[curIndex],
            style: TextStyle(color: ColorCommon.blue1, fontSize: 12.0),
          ));
    }
    return Padding(
        padding: const EdgeInsets.only(top: 4.0),
        child: Text(
          _titles[curIndex],
          style: TextStyle(color: ColorCommon.black1, fontSize: 12.0),
        ));
  }

  Image getTabImage(path) {
    return Image.asset(
      path,
      width: 20.0,
      height: 20.0,
    );
  }

  void initData() {
    _titles = ["首页", "分类", "扫一扫", "购物车", "我的"];

    _tabImages = [
      [getTabImage("images/home.png"), getTabImage("images/home.png")],
      [getTabImage("images/category.png"), getTabImage("images/category.png")],
      [
        getTabImage("images/home_share.png"),
        getTabImage("images/home_share.png")
      ],
      [
        getTabImage("images/shopping_cart.png"),
        getTabImage("images/shopping_cart.png")
      ],
      [getTabImage("images/mine.png"), getTabImage("images/mine.png")],
    ];
  }

  _onSelectTab(int tabIndex, String paramsStr) {
    setState(() {
      currentIndex = tabIndex;
    });
    if (tabIndex == 1) {
      Map<String, dynamic> params;
      if (paramsStr != null && paramsStr.isNotEmpty) {
        params = json.decode(paramsStr);
      }
      (_children[tabIndex] as CategoriesPage)
          ?.initData(params != null ? params['root_id'] : 0);
    }
  }

  Future _scan() async {
    ScanResult barcode;
    String errorStr;
    try {
      var options = ScanOptions(
        strings: {
          "cancel": "取消",
          "flash_on": "打开闪光灯",
          "flash_off": "关闭闪光灯",
        },
        android: AndroidOptions(
          useAutoFocus: true,
        ),
      );

      barcode = await BarcodeScanner.scan(options: options);
      int _pId = int.parse(barcode.rawContent);
      if (_pId != null && _pId > 0) {
        Navigator.of(context).push(MaterialPageRoute(builder: (_) {
          return GoodsDetailsPage(productId: _pId);
        }));
      }
      return;
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        errorStr = '未授权摄像头权限';
      } else {
        errorStr = 'Unknown error: $e';
      }
    } on FormatException {
      if (errorStr != null && errorStr.isNotEmpty) {
        errorStr = '数据解析有误, 请扫描正确的二维码';
      } else {
        return;
      }
    } catch (e) {
      errorStr = 'Unknown error: $e';
    }
    ToastUtil.showMessageToast(errorStr);
  }

  _showDialog() {
    showDialog<Null>(
      context: context,
      child: AlertDialog(content: Text('确定退出当前APP?'), actions: <Widget>[
        FlatButton(
            onPressed: () {
              Navigator.pop(context);
              if (Navigator.canPop(context)) {
                Navigator.pop(context);
              } else {
                SystemNavigator.pop();
              }
            },
            child: Text('确定')),
        FlatButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text('取消'))
      ]),
    );
  }

  /// 用户协议中“低调”文本的样式。
  final TextStyle _lowProfileStyle = TextStyle(
    fontSize: 12.0,
    color: Color(0xFF4A4A4A),
  );

  /// 用户协议中“高调”文本的样式。
  final TextStyle _highProfileStyle = TextStyle(
    fontSize: 12.0,
    color: Color(0xFF00CED2),
  );

  _showPrivacyDialog() {
    Text textContent = Text.rich(
      TextSpan(
        text:
            '    感谢您对本公司的支持!本公司非常重视您的个人信息和隐私保护。\n为了更好地保障您的个人权益，在您使用我们的产品前，\n请务必审慎阅读',
        style: _lowProfileStyle,
        children: [
          TextSpan(
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                String html = Uri.dataFromString(Api.privacyPolicy,
                    mimeType: 'text/html',
                    parameters: {'charset': 'utf-8'}).toString();
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return FWebviewScaffold(
                    url: html,
                    userAgent: Api.kWebViewUserAgent,
                    enableMessaging: true,
                    withJavascript: true,
                    clearCache: true,
                    appBar: AppBar(
                      title: Text("隐私政策"),
                    ),
                  );
                }));
              },
            text: '《隐私政策》',
            style: _highProfileStyle,
          ),
          TextSpan(
            text: '和',
            style: _lowProfileStyle,
          ),
          TextSpan(
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                String html = Uri.dataFromString(Api.userAgreement,
                    mimeType: 'text/html',
                    parameters: {'charset': 'utf-8'}).toString();
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return FWebviewScaffold(
                    url: html,
                    userAgent: Api.kWebViewUserAgent,
                    enableMessaging: true,
                    withJavascript: true,
                    clearCache: true,
                    appBar: AppBar(
                      title: Text("用户协议"),
                    ),
                  );
                }));
              },
            text: '《用户协议》',
            style: _highProfileStyle,
          ),
          TextSpan(
              text:
                  '内的所有条款，\n尤其是:\n 1.我们对您的个人信息的收集/保存/使用/对外提供/保护等规则条款，以及您的用户权利等条款;\n 2.约定我们的限制责任、免责条款;\n 3.其他以颜色或加粗进行标识的重要条款。\n如您对以上协议有任何疑问，\n可通过人工客服或发邮件至 2242686462@qq.com 与我们联系。您点击“同意并继续”的行为即表示您已阅读完毕并同意以上协议的全部内容。\n如您同意以上协议内容，请点击“同意”，开始使用我们的产品和服务!',
              style: _lowProfileStyle)
        ],
      ),
    );

    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      child: AlertDialog(content: textContent, actions: <Widget>[
        FlatButton(
            onPressed: () {
              Navigator.pop(context);
              User.saveIsShowPrivacy(true);
            },
            child: Text('同意')),
        FlatButton(
            onPressed: () {
              Navigator.pop(context);
              SystemNavigator.pop();
            },
            child: Text('拒绝'))
      ]),
    );
  }

  int _firstTime;
  Future<bool> _requestPop() {
    // _showDialog();
    // return Future.value(false);
    if (_firstTime == null ||
        _firstTime <= 0 ||
        DateTime.now().millisecondsSinceEpoch - _firstTime > 2000) {
      _firstTime = DateTime.now().millisecondsSinceEpoch;
      ToastUtil.showMessageToast('再按一次将退出当前APP');
      return Future.value(false);
    } else if (DateTime.now().millisecondsSinceEpoch - _firstTime < 2000) {
      SystemNavigator.pop();
      return Future.value(true);
    }
  }
}
